package L618;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: javase
 * @description: 合并区间
 * @author: luolidong
 * @create: 2021-06-17 22:57
 * @version: 1.0
 */
//[1,3][2,4],[4,6]
public class Demo {
    public List<List<Integer>> merge(int[][] intervals) {
        List<List<Integer>> list = new ArrayList<>();
        if (intervals.length == 0) return null;
        Arrays.sort(intervals, (x, y) -> {
            return x[0] - y[0];
        });
        int left = 0;
        int right = 0;
        int leftBound = intervals[0][0];
        int rightBound = intervals[0][1];
        while (right<intervals.length) {

            leftBound = intervals[left][0];
            rightBound = intervals[right][1];
            while (right < intervals.length && rightBound >= intervals[right][0]) {
                rightBound = intervals[right][1];
                right++;
            }
//            关键将right赋给left
            left = right;
            ArrayList<Integer> list1 = new ArrayList<>();
            list1.add(leftBound);
            list1.add(rightBound);
            list.add(list1);
        }
        return list;
    }

    public static void main(String[] args) {
        int[][] arr = new int[][]{{1, 3}, {2, 4}, {5, 7}};

        List<List<Integer>> merge = new Demo().merge(arr);
        for (List<Integer> l : merge) {
            System.out.println(l);
        }
    }
}
